<template>
    <div class="content-box">
        <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            accept=".jpg,.png,.gif"
            :auto-upload="false"
            :on-change="onchange"
        >
            <img
                v-if="base64Header || courseCover"
                :src="base64Header || coverImage(courseCover)"
                class="avatar"
                alt=""
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
import { FormPage } from "@/layout/mixin/iVue.js";
import { ossUpload } from "@/utils/file";

export default {
    mixins: [FormPage],
    props: {
        cover: {
            type: String,
            default: null
        },
        size:{
            type:Number,
            default: null
        }
    },
    data() {
        return {
            fileList: [],
            form: new FormData(),
            base64Header: null,
            courseCover: ""
        };
    },
    watch: {
        cover(val) {
            this.courseCover = val;
        }
    },
    created() {},
    methods: {
      /*  checkSize(file){
            const isLt2M = file.size / 1024 / 1024 < 1
            if(!isLt2M) {
                this.$message({
                    message: "上传文件大小不能超过 10MB!",
                    type: "warning"
                });
            }
            return isLt2M;
        },*/
        //图片上传
        onchange(file, fileList) {
            if(this.size){
                if (file.size > this.size){
                    this.$message.error("图片上传超过指定大小")
                    return
                }
            }
            if (fileList.length > 1) {
                fileList.splice(0, 1);
            }
            const elFile = fileList[0];
            file = fileList[0].raw;
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file);
            ossUpload("cdn", file.name, file, p => {
                elFile.percentage = p * 100;
                elFile.status = "uploading";
            }).then(result => {
                this.form.header = result;
                this.courseCover = result;
                elFile.status = "done";
                this.$emit("courseCoverImg", result);
            });
        }
    }
};
</script>
<style lang="css">
.content-box .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.content-box .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 118px;
    line-height: 118px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
